﻿using System;
using System.Net;
using System.Runtime.Serialization.Json;

namespace Twilight.TwitterData
{
    public class YahooPipesDataProvider : BaseDataProvider
    {
        private const string PipeUrlFormat = "http://pipes.yahooapis.com/pipes/pipe.run?_id=bmyAAovs3RGkGYkMBRNMsA&twitterUser={0}&count={1}&_render=json&{2}";

        private string pipeUrl;
        private DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(PipeResponse));

        public override void Initialize(string username, string count)
        {
            base.Initialize(username, count);

            pipeUrl = string.Format(PipeUrlFormat, username, count, DateTime.Now.Ticks);
            RequestTweets();
        }

        protected override void timer_Tick(object sender, EventArgs e)
        {
            RequestTweets();
        }

        private void RequestTweets()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(string.Format("{0}&{1}", pipeUrl, DateTime.Now.Ticks)));
            request.BeginGetResponse(new AsyncCallback(ResponseHandler), request);
        }

        private void ResponseHandler(IAsyncResult asyncResult)
        {
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var pipeResponse = json.ReadObject(response.GetResponseStream()) as PipeResponse;
                if (pipeResponse.value.items.Length == 1)
                {
                    OnTweetsUpdated(pipeResponse.value.items[0].status);
                }
            }
        }

        public class PipeResponse
        {
            public PipeResponseValue value { get; set; }
        }

        public class PipeResponseValue
        {
            public TwitterStatus[] items;
        }

        public class TwitterStatus
        {
            public Tweet[] status;
        }
    }
}
